package com.birdpiss.commons.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.birdpiss.commons.dao.interfaces.UserDao;
import com.birdpiss.commons.domain.User;

/**
 * The Class DefaultUserDao.
 *
 * @author mark
 */
@Repository("userDao")
public class DefaultUserDao extends SimpleJdbcTemplate implements UserDao {

	private static final Logger log = Logger.getLogger(UserDao.class);
	protected static final String [] COLUMNS = { "Id", "Name" };
	protected UserRowMapper userRowMapper = new UserRowMapper();

	protected static final String SELECT_ALL =
		"SELECT " + StringUtils.arrayToCommaDelimitedString(COLUMNS) +
		" FROM `user` " +
		"WHERE 1 = 1 " +
		"ORDER BY Id ASC";

	protected static final String SELECT_BY_ID =
		"SELECT " + StringUtils.arrayToCommaDelimitedString(COLUMNS) +
		" FROM `user` " +
		"WHERE Id = ?";

	/**
	 * Instantiates a new default user dao.
	 *
	 * @param dataSource the data source
	 */
	@Autowired
	public DefaultUserDao(@Qualifier("birdpiss") DataSource dataSource) {
		super(dataSource);
	}

	/* (non-Javadoc)
	 * @see com.birdpiss.commons.dao.interfaces.UserDao#getAllUsers()
	 */
	@Override
	public List<User> getAllUsers() {
		if (log.isDebugEnabled()) log.debug("Getting all users....");
		return this.query(SELECT_ALL, this.userRowMapper);
	}

	/* (non-Javadoc)
	 * @see com.birdpiss.commons.dao.interfaces.UserDao#getUser(java.lang.Integer)
	 */
	@Override
	public User getUser(Integer userId) {
		if (log.isDebugEnabled()) log.debug("Getting user id: " + userId);
		List<User> user = this.query(SELECT_BY_ID, this.userRowMapper, userId);
		return ((user != null) && (user.size() == 1)) ? user.get(0) : null;
	}

	/**
	 * The class UserRowMapper.
	 */
	protected class UserRowMapper implements ParameterizedRowMapper<User> {

		/* (non-Javadoc)
		 * @see org.springframework.jdbc.core.simple.ParameterizedRowMapper#mapRow(java.sql.ResultSet, int)
		 */
		@Override
		public User mapRow(ResultSet rs, int rowNum) throws SQLException {

			User user = new User();

			user.setId(rs.getInt(COLUMNS[0]));
			user.setName(rs.getString(COLUMNS[1]));

			return user;
		}
	}

}
